﻿using B.Auth.APi.Application.Command.Menus;
using B.Auth.APi.Application.Command.Menus.Dto;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;
using System.Threading.Tasks;

namespace B.Auth.APi.Application.CommandHand.Menuss
{
    public class MenusTreeCommandHand : IRequestHandler<MenusTreeCommand, ApiResult<List<MenusTreeDto>>>
    {

        private readonly IBaseRepository<MenuModel> _menu;

        public MenusTreeCommandHand(IBaseRepository<MenuModel> menu)
        {
            _menu = menu;
        }

        public  async Task<ApiResult<List<MenusTreeDto>>> Handle(MenusTreeCommand request, CancellationToken cancellationToken)
        {
            var result=new ApiResult<List<MenusTreeDto>>();
            var m = await GetMenusTreeAll(0);
            result.data = m;
            return await Task.FromResult(result);
        }


        public async Task<List<MenusTreeDto>> GetMenusTreeAll(int PID)
        {
            var menulist = _menu.GetAll().Where(x => x.PID == PID&&x.MenuDel==0).ToList();
                var list=new List<MenusTreeDto>();
            foreach (var item in menulist)
            {

                list.Add(new()
                {
                    label = item.MenuName,
                    id = item.Id,
                    children = await GetMenusTreeAll(item.Id)

                });

            }
            return list;


        }

    }
}
